﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PersistentManager.Descriptors;
using PersistentManager.Mapping;

namespace PersistentManager.Metadata.ExtractionRules
{
    internal class FieldExtraction : AbstractExtraction
    {
        protected override EntityMetadata BeginExtraction( EntityMetadata metadata , XmlEntityMapping mapping )
        {
            foreach ( Field field in mapping.Fields )
            {
                if ( !field.IsEmbedded() )
                {
                    PropertyMetadata property = ExtractField(metadata, mapping, field);

                    metadata.ColumnInfoBag.Add(property);
                }
            }

            return metadata;
        }

        protected PropertyMetadata ExtractField(EntityMetadata metadata, XmlEntityMapping mapping, Field field)
        {
            PropertyMetadata property = new PropertyMetadata()
            {
                DeclaringType = mapping.Type,
                ClassDefinationName = field.Property.Name,
                PropertyType = field.Property.PropertyType,
                MappingName = field.Name,
                IsUniqueIdentifier = field.IsUnique,
                IsAutoGenerated = field.AutoKey,
                DbType = field.DbDataType,
                AllowNull = field.AllowNullValue,
                IsManyToOne = false,
                ExcludeValue = field.Exclude.IsNullOrEmpty() ? null : DataType.ConvertValue(field.Property.PropertyType, field.Exclude),
                KeyPriority = field.Priority,
                Length = 0
            };

            return property;
        }

        protected override void EndExtraction()
        {
            return;
        }

        protected override void ValidateMapping()
        {
            return;
        }
    }
}
